package com.cssl.gulimall.member.controller;

import com.cssl.common.exception.BizCodeEnume;
import com.cssl.common.to.member.MemberUserLoginTO;
import com.cssl.common.to.member.MemberUserRegisterTO;
import com.cssl.common.utils.R;
import com.cssl.common.vo.auth.GiteeUser;
import com.cssl.common.vo.auth.UserForgetVO;
import com.cssl.common.vo.auth.UserLoginVO;
import com.cssl.gulimall.member.entity.MemberEntity;
import com.cssl.gulimall.member.exception.PhoneException;
import com.cssl.gulimall.member.exception.UsernameException;
import com.cssl.gulimall.member.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/member/member")
public class MemberController {
    @Autowired
    private MemberService memberService;

    @GetMapping("/test")
    public R test(){
        return R.ok().put("success","ok");
    }

    @PostMapping("/register")
    public R register(@RequestBody MemberUserRegisterTO user){
        try {
            memberService.regist(user);
            return R.ok();
        } catch (PhoneException e) {
            return R.error(BizCodeEnume.PHONE_EXIST_EXCEPTION);
        } catch (UsernameException e){
            return R.error(BizCodeEnume.USER_EXIST_EXCEPTION);
        } catch (Exception e){
            return R.error(e.getMessage());
        }
    }

    /*
    登录
     */
    @PostMapping("/login")
    public R login(@RequestBody MemberUserLoginTO user){
        System.out.println("member==login");
        try {
            MemberEntity entity = memberService.login(user);
            if(entity == null){
                return R.error(BizCodeEnume.LOGINACCT_PASSWORD_EXCEPTION);
            }
            return R.ok().setData(entity);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    @PostMapping("/oauth2Login")
    public R oauth2Login(@RequestBody GiteeUser user){
        try {
            MemberEntity entity = memberService.login(user);
            return R.ok().setData(entity);
        } catch (Exception ex) {
            return R.error(ex.getMessage());
        }
    }

    /**
     * 判断号码是否绑定账户
     */
    @PostMapping("/hasPhoneBiding")
    public R hasPhoneBiding(@RequestParam String phone){
        MemberEntity entity = memberService.hasPhoneBiding(phone);
        if(entity != null){
            return R.ok();
        }else {
            return R.error();
        }
    }

    /**
     * 修改密码
     */
    @PostMapping("/changePwd")
    public R changePwd(@RequestBody UserForgetVO userForgetVO){
        try {
            memberService.changePwd(userForgetVO);
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }
}
